#!/bin/bash
# this script truncate squid access log file.

COMMON_VARIABLES=(`perl $TWMFOLDER/bin/get_varMultipleValue.pl cp rm gzip sed date find _DEFAULT_`)
cp=${COMMON_VARIABLES[0]}
rm=${COMMON_VARIABLES[1]}
gzip=${COMMON_VARIABLES[2]}
sed=${COMMON_VARIABLES[3]}
date=${COMMON_VARIABLES[4]}
find=${COMMON_VARIABLES[5]}

MODULE_VARIABLES=(`perl $TWMFOLDER/bin/get_varMultipleValue.pl sarg sarg_conf max_log_size max_log_age http_logging`)
sarg=${MODULE_VARIABLES[0]}
sarg_conf=${MODULE_VARIABLES[1]}
max_size=${MODULE_VARIABLES[2]}
max_age=${MODULE_VARIABLES[3]}

SQUIDS=(`perl $TWMFOLDER/modules/http_logging/get_squid_data.pl`)

for item in ${SQUIDS[*]}
do
	SQUID_SETTINGS=(`echo $item | $sed -e "s/:/ /g"`)
	log_dir=${SQUID_SETTINGS[2]}
	access_log=${SQUID_SETTINGS[3]}

	d1=`$date +%d`
	m1=`$date +%m`
	y1=`$date +%Y`

	access_log_new=`echo ${access_log}_$y1$m1$d1`
	temp_file="tmp.log"

	last_months='1'

	m=`expr $m1 - $last_months`
	y=$y1
	if [ $m -eq 0 ] ; then
	    m=12
	    y=`expr $y - 1`
	fi

	if [ $m -lt 10 ] ; then
	    m="0$m"
	fi

	cd $log_dir

	let "max_size_MB = max_size*1024*1024"
	access_log_size=`ls -l $access_log | gawk '{print $5}'`
	if [ $access_log_size -ge $max_size_MB ]; then
		$cp $access_log $access_log_new
		$gzip $access_log_new
		$sarg -split -f $sarg_conf -d $d1/$m/$y-$d1/$m1/$y1 > $temp_file
		$cp -f $temp_file $access_log
		$rm $temp_file
	fi
	
	$find ./ -maxdepth 1 -type f -regex .+/${access_log}_.+\.gz -ctime +$max_age -exec $rm -fr {} \;

done

exit 0
